<?php

// 公共助手函数

use Symfony\Component\VarExporter\VarExporter;
use think\config;
use fast\IDUtil;
if (!function_exists('__')) {

    /**
     * 获取语言变量值
     * @param string $name 语言变量名
     * @param array  $vars 动态变量值
     * @param string $lang 语言
     * @return mixed
     */
    function __($name, $vars = [], $lang = '')
    {
        if (is_numeric($name) || !$name) {
            return $name;
        }
        if (!is_array($vars)) {
            $vars = func_get_args();
            array_shift($vars);
            $lang = '';
        }
        return \think\Lang::get($name, $vars, $lang);
    }
}

if (!function_exists('format_bytes')) {

    /**
     * 将字节转换为可读文本
     * @param int    $size      大小
     * @param string $delimiter 分隔符
     * @return string
     */
    function format_bytes($size, $delimiter = '')
    {
        $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
        for ($i = 0; $size >= 1024 && $i < 6; $i++) {
            $size /= 1024;
        }
        return round($size, 2) . $delimiter . $units[$i];
    }
}

if (!function_exists('datetime')) {

    /**
     * 将时间戳转换为日期时间
     * @param int    $time   时间戳
     * @param string $format 日期时间格式
     * @return string
     */
    function datetime($time, $format = 'Y-m-d H:i:s')
    {
        $time = is_numeric($time) ? $time : strtotime($time);
        return date($format, $time);
    }
}

if (!function_exists('human_date')) {

    /**
     * 获取语义化时间
     * @param int $time  时间
     * @param int $local 本地时间
     * @return string
     */
    function human_date($time, $local = null)
    {
        return \fast\Date::human($time, $local);
    }
}

if (!function_exists('cdnurl')) {

    /**
     * 获取上传资源的CDN的地址
     * @param string  $url    资源相对地址
     * @param boolean $domain 是否显示域名 或者直接传入域名
     * @return string
     */
    function cdnurl($url, $domain = false)
    {
        $regex = "/^((?:[a-z]+:)?\/\/|data:image\/)(.*)/i";
        $cdnurl = \think\Config::get('upload.cdnurl');
        $url = preg_match($regex, $url) || ($cdnurl && stripos($url, $cdnurl) === 0) ? $url : $cdnurl . $url;
        if ($domain && !preg_match($regex, $url)) {
            $domain = is_bool($domain) ? request()->domain() : $domain;
            $url = $domain . $url;
        }
        return $url;
    }
}


if (!function_exists('is_really_writable')) {

    /**
     * 判断文件或文件夹是否可写
     * @param string $file 文件或目录
     * @return    bool
     */
    function is_really_writable($file)
    {
        if (DIRECTORY_SEPARATOR === '/') {
            return is_writable($file);
        }
        if (is_dir($file)) {
            $file = rtrim($file, '/') . '/' . md5(mt_rand());
            if (($fp = @fopen($file, 'ab')) === false) {
                return false;
            }
            fclose($fp);
            @chmod($file, 0777);
            @unlink($file);
            return true;
        } elseif (!is_file($file) or ($fp = @fopen($file, 'ab')) === false) {
            return false;
        }
        fclose($fp);
        return true;
    }
}

if (!function_exists('rmdirs')) {

    /**
     * 删除文件夹
     * @param string $dirname  目录
     * @param bool   $withself 是否删除自身
     * @return boolean
     */
    function rmdirs($dirname, $withself = true)
    {
        if (!is_dir($dirname)) {
            return false;
        }
        $files = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($dirname, RecursiveDirectoryIterator::SKIP_DOTS),
            RecursiveIteratorIterator::CHILD_FIRST
        );

        foreach ($files as $fileinfo) {
            $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
            $todo($fileinfo->getRealPath());
        }
        if ($withself) {
            @rmdir($dirname);
        }
        return true;
    }
}

if (!function_exists('copydirs')) {

    /**
     * 复制文件夹
     * @param string $source 源文件夹
     * @param string $dest   目标文件夹
     */
    function copydirs($source, $dest)
    {
        if (!is_dir($dest)) {
            mkdir($dest, 0755, true);
        }
        foreach (
            $iterator = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS),
                RecursiveIteratorIterator::SELF_FIRST
            ) as $item
        ) {
            if ($item->isDir()) {
                $sontDir = $dest . DS . $iterator->getSubPathName();
                if (!is_dir($sontDir)) {
                    mkdir($sontDir, 0755, true);
                }
            } else {
                copy($item, $dest . DS . $iterator->getSubPathName());
            }
        }
    }
}

if (!function_exists('mb_ucfirst')) {
    function mb_ucfirst($string)
    {
        return mb_strtoupper(mb_substr($string, 0, 1)) . mb_strtolower(mb_substr($string, 1));
    }
}

if (!function_exists('addtion')) {

    /**
     * 附加关联字段数据
     * @param array $items  数据列表
     * @param mixed $fields 渲染的来源字段
     * @return array
     */
    function addtion($items, $fields)
    {
        if (!$items || !$fields) {
            return $items;
        }
        $fieldsArr = [];
        if (!is_array($fields)) {
            $arr = explode(',', $fields);
            foreach ($arr as $k => $v) {
                $fieldsArr[$v] = ['field' => $v];
            }
        } else {
            foreach ($fields as $k => $v) {
                if (is_array($v)) {
                    $v['field'] = isset($v['field']) ? $v['field'] : $k;
                } else {
                    $v = ['field' => $v];
                }
                $fieldsArr[$v['field']] = $v;
            }
        }
        foreach ($fieldsArr as $k => &$v) {
            $v = is_array($v) ? $v : ['field' => $v];
            $v['display'] = isset($v['display']) ? $v['display'] : str_replace(['_ids', '_id'], ['_names', '_name'], $v['field']);
            $v['primary'] = isset($v['primary']) ? $v['primary'] : '';
            $v['column'] = isset($v['column']) ? $v['column'] : 'name';
            $v['model'] = isset($v['model']) ? $v['model'] : '';
            $v['table'] = isset($v['table']) ? $v['table'] : '';
            $v['name'] = isset($v['name']) ? $v['name'] : str_replace(['_ids', '_id'], '', $v['field']);
        }
        unset($v);
        $ids = [];
        $fields = array_keys($fieldsArr);
        foreach ($items as $k => $v) {
            foreach ($fields as $m => $n) {
                if (isset($v[$n])) {
                    $ids[$n] = array_merge(isset($ids[$n]) && is_array($ids[$n]) ? $ids[$n] : [], explode(',', $v[$n]));
                }
            }
        }
        $result = [];
        foreach ($fieldsArr as $k => $v) {
            if ($v['model']) {
                $model = new $v['model'];
            } else {
                $model = $v['name'] ? \think\Db::name($v['name']) : \think\Db::table($v['table']);
            }
            $primary = $v['primary'] ? $v['primary'] : $model->getPk();
            $result[$v['field']] = isset($ids[$v['field']]) ? $model->where($primary, 'in', $ids[$v['field']])->column("{$primary},{$v['column']}") : [];
        }

        foreach ($items as $k => &$v) {
            foreach ($fields as $m => $n) {
                if (isset($v[$n])) {
                    $curr = array_flip(explode(',', $v[$n]));

                    $v[$fieldsArr[$n]['display']] = implode(',', array_intersect_key($result[$n], $curr));
                }
            }
        }
        return $items;
    }
}

if (!function_exists('var_export_short')) {

    /**
     * 使用短标签打印或返回数组结构
     * @param mixed   $data
     * @param boolean $return 是否返回数据
     * @return string
     */
    function var_export_short($data, $return = true)
    {
        return var_export($data, $return);
        $replaced = [];
        $count = 0;

        //判断是否是对象
        if (is_resource($data) || is_object($data)) {
            return var_export($data, $return);
        }

        //判断是否有特殊的键名
        $specialKey = false;
        array_walk_recursive($data, function (&$value, &$key) use (&$specialKey) {
            if (is_string($key) && (stripos($key, "\n") !== false || stripos($key, "array (") !== false)) {
                $specialKey = true;
            }
        });
        if ($specialKey) {
            return var_export($data, $return);
        }
        array_walk_recursive($data, function (&$value, &$key) use (&$replaced, &$count, &$stringcheck) {
            if (is_object($value) || is_resource($value)) {
                $replaced[$count] = var_export($value, true);
                $value = "##<{$count}>##";
            } else {
                if (is_string($value) && (stripos($value, "\n") !== false || stripos($value, "array (") !== false)) {
                    $index = array_search($value, $replaced);
                    if ($index === false) {
                        $replaced[$count] = var_export($value, true);
                        $value = "##<{$count}>##";
                    } else {
                        $value = "##<{$index}>##";
                    }
                }
            }
            $count++;
        });

        $dump = var_export($data, true);

        $dump = preg_replace('#(?:\A|\n)([ ]*)array \(#i', '[', $dump); // Starts
        $dump = preg_replace('#\n([ ]*)\),#', "\n$1],", $dump); // Ends
        $dump = preg_replace('#=> \[\n\s+\],\n#', "=> [],\n", $dump); // Empties
        $dump = preg_replace('#\)$#', "]", $dump); //End

        if ($replaced) {
            $dump = preg_replace_callback("/'##<(\d+)>##'/", function ($matches) use ($replaced) {
                return isset($replaced[$matches[1]]) ? $replaced[$matches[1]] : "''";
            }, $dump);
        }

        if ($return === true) {
            return $dump;
        } else {
            echo $dump;
        }
    }
}

if (!function_exists('letter_avatar')) {
    /**
     * 首字母头像
     * @param $text
     * @return string
     */
    function letter_avatar($text)
    {
        $total = unpack('L', hash('adler32', $text, true))[1];
        $hue = $total % 360;
        list($r, $g, $b) = hsv2rgb($hue / 360, 0.3, 0.9);

        $bg = "rgb({$r},{$g},{$b})";
        $color = "#ffffff";
        $first = mb_strtoupper(mb_substr($text, 0, 1));
        $src = base64_encode('<svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="100" width="100"><rect fill="' . $bg . '" x="0" y="0" width="100" height="100"></rect><text x="50" y="50" font-size="50" text-copy="fast" fill="' . $color . '" text-anchor="middle" text-rights="admin" dominant-baseline="central">' . $first . '</text></svg>');
        $value = 'data:image/svg+xml;base64,' . $src;
        return $value;
    }
}

if (!function_exists('hsv2rgb')) {
    function hsv2rgb($h, $s, $v)
    {
        $r = $g = $b = 0;

        $i = floor($h * 6);
        $f = $h * 6 - $i;
        $p = $v * (1 - $s);
        $q = $v * (1 - $f * $s);
        $t = $v * (1 - (1 - $f) * $s);

        switch ($i % 6) {
            case 0:
                $r = $v;
                $g = $t;
                $b = $p;
                break;
            case 1:
                $r = $q;
                $g = $v;
                $b = $p;
                break;
            case 2:
                $r = $p;
                $g = $v;
                $b = $t;
                break;
            case 3:
                $r = $p;
                $g = $q;
                $b = $v;
                break;
            case 4:
                $r = $t;
                $g = $p;
                $b = $v;
                break;
            case 5:
                $r = $v;
                $g = $p;
                $b = $q;
                break;
        }

        return [
            floor($r * 255),
            floor($g * 255),
            floor($b * 255)
        ];
    }
}

if (!function_exists('check_nav_active')) {
    /**
     * 检测会员中心导航是否高亮
     */
    function check_nav_active($url, $classname = 'active')
    {
        $auth = \app\common\library\Auth::instance();
        $requestUrl = $auth->getRequestUri();
        $url = ltrim($url, '/');
        return $requestUrl === str_replace(".", "/", $url) ? $classname : '';
    }
}

if (!function_exists('check_cors_request')) {
    /**
     * 跨域检测
     */
    function check_cors_request()
    {
        if (isset($_SERVER['HTTP_ORIGIN']) && $_SERVER['HTTP_ORIGIN']) {
            $info = parse_url($_SERVER['HTTP_ORIGIN']);
            $domainArr = explode(',', config('fastadmin.cors_request_domain'));
            $domainArr[] = request()->host(true);
            if (in_array("*", $domainArr) || in_array($_SERVER['HTTP_ORIGIN'], $domainArr) || (isset($info['host']) && in_array($info['host'], $domainArr))) {
                header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
            } else {
                header('HTTP/1.1 403 Forbidden');
                exit;
            }

            header('Access-Control-Allow-Credentials: true');
            header('Access-Control-Max-Age: 86400');

            if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
                if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
                    header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
                }
                if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
                    header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
                }
                exit;
            }
        }
    }
}

if (!function_exists('xss_clean')) {
    /**
     * 清理XSS
     */
    function xss_clean($content, $is_image = false)
    {
        return \app\common\library\Security::instance()->xss_clean($content, $is_image);
    }
}

function getDomain(){
//    if(Request::instance()->isMobile()){
//        return Config::get('m_domain');
//    } else {
        return Config::get('domain');
//    }
//        $host = $_SERVER['HTTP_HOST'];
//        if($host == Config::get('m_http_host')){
//            return Config::get('m_domain');
//        } else {
//            return Config::get('domain');
//        }
}
function getImgDomain(){
//    if(Request::instance()->isMobile()){
//        return Config::get('m_domain');
//    } else {
    return Config::get('img_domain');
//    }
//        $host = $_SERVER['HTTP_HOST'];
//        if($host == Config::get('m_http_host')){
//            return Config::get('m_domain');
//        } else {
//            return Config::get('domain');
//        }
}
function getMDomain(){
//    if(Request::instance()->isMobile()){
//        return Config::get('m_domain');
//    } else {
    return Config::get('m_domain');
//    }
//        $host = $_SERVER['HTTP_HOST'];
//        if($host == Config::get('m_http_host')){
//            return Config::get('m_domain');
//        } else {
//            return Config::get('domain');
//        }
}
function getMhost(){
    return Config::get('m_host');
}
function getHost(){
    return Config::get('host');
}

function getCiUrl($hanzi){
    return getDomain()."/ciyu/".$hanzi;
}

function getMCiUrl($hanzi){
    return getMDomain()."/ciyu/".$hanzi;
}

function getZiUrl($hanzi){
    return getDomain()."/hanzi/".$hanzi."/";
}

function getMZiUrl($hanzi){
    return getMDomain()."/hanzi/".$hanzi."/";
}
function getMainDomain(){
    return str_replace("www.","",Config::get('host'));
}
function mkdirs($pathname, $mode = 0755)
{
    is_dir(dirname($pathname)) || mkdirs(dirname($pathname), $mode);
    return is_dir($pathname) || @ mkdir($pathname, $mode);
}

/**
 * 方法描述：字符截取 支持UTF8/GBK
 * @param $string
 * @param int $length
 * @param string $dot
 * @param string $charset
 * @return mixed|string
 * 注意：
 */
function str_cut($string, $length = 120, $dot = '...', $charset = 'UTF-8')
{
    if (empty($length)) {
        $length = 120;
    }
    if(empty($string)){
        return "";
    }
    $str = strip_tags($string);
    if(empty($str)){
        return "";
    }
    return mb_substr($str, 0, $length, $charset) . $dot;
}

function filter_p($content){
    return str_replace(["<p>","</p>"],["",""],$content);
}



/**
 * @param $allCount 总共条数
 * @param $dir 目录
 * @param $currentPage 当前页
 * @param int $pageCount每页多少条
 * @return string
 */
function getYingshiPage($allCount,$dir,$currentPage,$pageCount=10,$typeid=0,$list='list_',$isM=false)
{
    $suffix = ".html";
    if($isM){
        $domain = getMDomain();
    } else {
        $domain = getDomain();
    }
    $url = $domain."/".$dir."/".$list;
//    echo $url;exit;
    if(!empty($typeid)){
        $url .=$typeid."_";
    }

    //最大页数
    $maxPage = ceil($allCount / $pageCount);
    if($currentPage > $maxPage){
        $currentPage = $maxPage;
    }
    $html = '';
    $lastPage = $currentPage-1;
    if($currentPage == 1){
        $lastPage = 1;
    }

    $html .= '<a href="' . $url . '1' . $suffix . '" class="long ">首页</a>';
    $html .='<a href="'.$url.$lastPage.$suffix.'" class="long" title="上一页" target="_self">上页</a>';
    if($currentPage > 10){
        $html .='<a class="long waphidden">...</a>';
    }
//    for ($i = 1; $i <= $maxPage; $i++) {
//        if ($i == $currentPage) {
//            $html .= '<a class="long current  waphidden" href="' . getDomain() . '/' . $dir . '/list_' . $i . '.html">' . $i . '</a>';
//        } else {
//            $html .= '<a class="long  waphidden" href="' . getDomain() . '/' . $dir . '/list_' . $i . '.html">' . $i . '</a>';
//        }
//
//    }

    for($i=$currentPage-10;$i<$currentPage-1;$i++){
        if($i == 0){
            $html .='<a class="long  waphidden" href="'.$url."1".$suffix.'" target="_self">1</a>';
        } else {
            if($i > 0){
                $html .='<a class="long  waphidden" href="'.$url.($i+1).$suffix.'" target="_self">'.($i+1).'</a>';
            }
        }

    }
    $html .='<a class="long current " href="'.$url.($currentPage).$suffix.'" target="_self">'.($currentPage).'</a>';
    for($i=$currentPage+1;$i<$currentPage+10;$i++){
        if($i <= $maxPage){
            $html .='<a class="long  waphidden" href="'.$url.($i).$suffix.'" target="_self">'.($i).'</a>';
        }
    }
    if($currentPage < ($maxPage-9)){
        $html .='<a class="long waphidden">...</a>';
    }

    $nextPage = $currentPage +1;
    if($maxPage == $currentPage){
        $nextPage = $currentPage;
    }

    $html .='<a href="'.$url.$nextPage.$suffix.'" class="long" title="下一页" target="_self">下页</a>';
    $html .= '<a href="' . $url . $maxPage . $suffix. '" class="long ">末页</a>';
    return $html;
}



/**
 * @param $allCount 总共条数
 * @param $dir 目录
 * @param $currentPage 当前页
 * @param int $pageCount每页多少条
 * @return string
 */
function getPage($allCount,$dir,$currentPage,$pageCount=10,$typeid=0,$list='list_',$isM=false)
{
    $suffix = "";
    if($isM){
        $domain = getMDomain();
    } else {
        $domain = getDomain();
    }
    $url = $domain.$dir."/".$list;
//    echo $url;exit;
    if(!empty($typeid)){
        $url .=$typeid."_";
    }

    //最大页数
    $maxPage = ceil($allCount / $pageCount);
    if($currentPage > $maxPage){
        $currentPage = $maxPage;
    }
    $html = '';
    $lastPage = $currentPage-1;
    if($currentPage == 1){
        $lastPage = 1;
    }

//    $html .= '<a href="' . $url . '1' . $suffix . '" class="page-number ">← Previous</a>';

    $html .='<a href="'.$url.$lastPage.$suffix.'" class="page-number" title="Previous" target="_self">← Previous</a>';
    if($currentPage > 3){
        $html .='<a class="page-number">...</a>';
    }
//    for ($i = 1; $i <= $maxPage; $i++) {
//        if ($i == $currentPage) {
//            $html .= '<a class="long current  waphidden" href="' . getDomain() . '/' . $dir . '/list_' . $i . '.html">' . $i . '</a>';
//        } else {
//            $html .= '<a class="long  waphidden" href="' . getDomain() . '/' . $dir . '/list_' . $i . '.html">' . $i . '</a>';
//        }
//
//    }

    for($i=$currentPage-3;$i<$currentPage-1;$i++){
        if($i == 0){
            $html .='<a class="page-number" href="'.$url."1".$suffix.'" target="_self">1</a>';
        } else {
            if($i > 0){
                $html .='<a class="page-number" href="'.$url.($i+1).$suffix.'" target="_self">'.($i+1).'</a>';
            }
        }

    }
    $html .='<a class="page-number active" href="'.$url.($currentPage).$suffix.'" target="_self">'.($currentPage).'</a>';
    for($i=$currentPage+1;$i<$currentPage+3;$i++){
        if($i <= $maxPage){
            $html .='<a class="page-number" href="'.$url.($i).$suffix.'" target="_self">'.($i).'</a>';
        }
    }
    if($currentPage < ($maxPage-2)){
        $html .='<a class="page-number">...</a>';
    }

    $nextPage = $currentPage +1;
    if($maxPage == $currentPage){
        $nextPage = $currentPage;
    }

    $html .='<a href="'.$url.$nextPage.$suffix.'" class="page-number" title="Next" target="_self">Next →</a>';
//    $html .= '<a href="' . $url . $maxPage . $suffix. '" class="long ">末页</a>';
    return $html;
}


/**
 * @param $allCount 总共条数
 * @param $dir 目录
 * @param $currentPage 当前页
 * @param int $pageCount每页多少条
 * @return string
 */
function getMPage($allCount,$dir,$currentPage,$pageCount=10,$typeid=0,$list='list_')
{
    $suffix = ".html";
    $url = getMDomain().$dir."/".$list;
//    echo $url;exit;
    if(!empty($typeid)){
        $url .=$typeid."_";
    }

    //最大页数
    $maxPage = ceil($allCount / $pageCount);
    if($currentPage > $maxPage){
        $currentPage = $maxPage;
    }
    $html = '';
    $lastPage = $currentPage-1;
    if($currentPage == 1){
        $lastPage = 1;
    }

    $html .= '<a href="' . $url . '1' . $suffix . '" class="long ">首页</a>';
    $html .='<a href="'.$url.$lastPage.$suffix.'" class="long" title="上一页" target="_self">上页</a>';
//    if($currentPage > 3){
//        $html .='<a class="long waphidden">...</a>';
//    }
//    for ($i = 1; $i <= $maxPage; $i++) {
//        if ($i == $currentPage) {
//            $html .= '<a class="long current  waphidden" href="' . getDomain() . '/' . $dir . '/list_' . $i . '.html">' . $i . '</a>';
//        } else {
//            $html .= '<a class="long  waphidden" href="' . getDomain() . '/' . $dir . '/list_' . $i . '.html">' . $i . '</a>';
//        }
//
//    }

//    for($i=$currentPage-3;$i<$currentPage-1;$i++){
//        if($i == 0){
//            $html .='<a class="long  waphidden" href="'.$url."1".$suffix.'" target="_self">1</a>';
//        } else {
//            if($i > 0){
//                $html .='<a class="long  waphidden" href="'.$url.($i+1).$suffix.'" target="_self">'.($i+1).'</a>';
//            }
//        }
//
//    }
    $html .='<a class="long current " href="'.$url.($currentPage).$suffix.'" target="_self">'.($currentPage).'</a>';
//    for($i=$currentPage+1;$i<$currentPage+3;$i++){
//        if($i <= $maxPage){
//            $html .='<a class="long  waphidden" href="'.$url.($i).$suffix.'" target="_self">'.($i).'</a>';
//        }
//    }
//    if($currentPage < ($maxPage-2)){
//        $html .='<a class="long waphidden">...</a>';
//    }

    $nextPage = $currentPage +1;
    if($maxPage == $currentPage){
        $nextPage = $currentPage;
    }

    $html .='<a href="'.$url.$nextPage.$suffix.'" class="long" title="下一页" target="_self">下页</a>';
    $html .= '<a href="' . $url . $maxPage . $suffix. '" class="long ">末页</a>';
    return $html;
}





/**
 * 伪造随机ip
 * @param type $url
 * @return type
 */
function _get_url($url) {
    $ifpost = 0;
    $datafields = '';
    $cookiefile = '';
    $v = false;
    //构造随机ip
    $ip_long = array(
        array('607649792', '608174079'), //36.56.0.0-36.63.255.255
        array('1038614528', '1039007743'), //61.232.0.0-61.237.255.255
        array('1783627776', '1784676351'), //106.80.0.0-106.95.255.255
        array('2035023872', '2035154943'), //121.76.0.0-121.77.255.255
        array('2078801920', '2079064063'), //123.232.0.0-123.235.255.255
        array('-1950089216', '-1948778497'), //139.196.0.0-139.215.255.255
        array('-1425539072', '-1425014785'), //171.8.0.0-171.15.255.255
        array('-1236271104', '-1235419137'), //182.80.0.0-182.92.255.255
        array('-770113536', '-768606209'), //210.25.0.0-210.47.255.255
        array('-569376768', '-564133889'), //222.16.0.0-222.95.255.255
    );
    $rand_key = mt_rand(0, 9);
    $ip = long2ip(mt_rand($ip_long[$rand_key][0], $ip_long[$rand_key][1]));
//模拟http请求header头
    $header = array("Connection: Keep-Alive", "Accept: text/html, application/xhtml+xml, */*", "Pragma: no-cache", "Accept-Language: zh-Hans-CN,zh-Hans;q=0.8,en-US;q=0.5,en;q=0.3", "User-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)", 'CLIENT-IP:' . $ip, 'X-FORWARDED-FOR:' . $ip);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, $v);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    $ifpost && curl_setopt($ch, CURLOPT_POST, $ifpost);
    $ifpost && curl_setopt($ch, CURLOPT_POSTFIELDS, $datafields);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    $cookiefile && curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiefile);
    $cookiefile && curl_setopt($ch, CURLOPT_COOKIEJAR, $cookiefile);
    curl_setopt($ch, CURLOPT_TIMEOUT, 60); //允许执行的最长秒数
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    $ok = curl_exec($ch);


    curl_close($ch);
    unset($ch);
    return $ok;
}

function hanziToPinyin($string){
    $enString = "";
    $pinyin = new \Overtrue\Pinyin\Pinyin('Overtrue\Pinyin\MemoryFileDictLoader');
    if(mb_strlen($string) > 3){
        $enString = $pinyin->abbr($string, '');
    } else {
        $enString = $pinyin->permalink($string,"");
    }
    return $enString;
}


function replaceSpace($str){
    $search = array(" ", "　", "\n", "\r", "\t", "<br>","        ");
    $replace = array("", "", "", "", "", "xiaopzi","");
    $return = str_replace($search, $replace, $str);
    if($return == '<p></p>'){
        return "";
    } else {
        return $return;
    }
}
function replaceHtml($str){
    $search = array("<strong>", "</strong>","<br />");
    $replace = array("", "", "<br/><span class='indent'>占位</span>");
    $return = str_replace($search, $replace, $str);
    return $return;
}


function replaceRenwuByContent($content){

    $searchArr = \think\Config::get('search');
    $replaceArr = \think\Config::get('replace');
//        print_r($replaceArr);exit;
    $content = str_replace($searchArr,$replaceArr,$content);

    return $content;

}

function replaceRenwuByContentByTitle($content,$title){

    $searchArr = \think\Config::get('search');
    $replaceArr = \think\Config::get('replace');

    $content = str_replace('title="'.$title.'"','biaoti_title_no_replace',$content);

    $searchStr = "title='".$title."'";
    $replaceStr = '__xiaopzi__';
    $content = str_replace($searchStr,$replaceStr,$content);


//        print_r($replaceArr);exit;
    $content = str_replace($searchArr,$replaceArr,$content);
//        echo $content;

    $content = str_replace($replaceStr,$searchStr,$content);
    $content = str_replace('biaoti_title_no_replace','title="'.$title.'"',$content);
//    echo $content;exit;
    return $content;

}
//id加密
function encodeId($id){

    return IDUtil::encode($id);
}
//id解密
function decodeId($jiami){
    $id = IDUtil::decode($jiami);
//    echo $id;exit;
    return $id;
}


function getChengyuArticleUrl($string){
    if(empty($string)){
        return getDomain()."/index.html";
    }
    return getDomain()."/chengyu/".$string;
}

function getMChengyuArticleUrl($string){
    if(empty($string)){
        return getMDomain()."/index.html";
    }
    return getMDomain()."/chengyu/".$string;
}


function getChengyuDomain(){
    return Config::get('domain');
}
function getMChengyuDomain(){
    return Config::get('m_domain');
}

function getArticleUrl($urlPath){

    return getDomain()."/".$urlPath;
}
function getMArticleUrl($id,$categoryId,$categoryPid){
    $list = Config::get("type");
    if($categoryId == $categoryPid){//一级分类
        $dir = $list[$categoryId]['type'];
    } else {
        $dir = $list[$categoryPid]['type'];
        $sonArr = $list[$categoryPid]['son'];
        $dir .="/".$sonArr[$categoryId]['type'];
    }
    return getMDomain()."/".$dir."/".$id.".html";
}

function getSonCategoryUrl(){
    $list = Config::get("type");
    $return = [];
    if(!empty($list)){
        foreach($list as $k=>$v){
            foreach($v['son'] as $key=>$val){
                $temp = [
                  'name' => $val['name'],
                  'url' => $val['url'],
                  'm_url' => $val['m_url'],
                ];
                $return[$val['id']] = $temp;
            }
        }
    }
    return $return;
}

//过滤空格
function myTrim($str) {
    $search = array(" ", "　", "\n", "\r", "\t", "<br>","<br >"," <br/>","<br />","    ");
    $replace = array("", "", "", "", "", "","","","","");
    return str_replace($search, $replace, $str);
}

/**
 * 删除结尾数字
 * @param $str
 */
function delStringEndNum($str){
//    $str = '123abc456';
    $len = strlen($str) - 1;
    while (is_numeric(substr($str, $len, 1))) {

        $len--;
    }
    $str = substr($str, 0, $len + 1);
    return $str;
//    $start = 0;
//    while (is_numeric(substr($str, $start, 1))) {
//        $start++;
//    }
//    $str = substr($str, $start);
}

/**
 * 删除字符串模板数组里的字
 */
function delStringEndArrString($str){
    $len = mb_strlen($str) - 1;
//    echo $len;
    $arr = ['篇'];
//    echo mb_substr($str, $len, 1)."\r\n";
//    exit;
    while (in_array(mb_substr($str, $len, 1),$arr)) {

        $len--;
    }

    $str = mb_substr($str, 0, $len + 1);
    return $str;

}

function getSeoTitle($title,$categoryPid,$categoryId){
    $list = Config::get("type");
    $pidArr = $list[$categoryPid];
    $sonArr = $pidArr['son'][$categoryId];
//    print_r($sonArr);exit;


    return $title."_".$pidArr['name'].$sonArr['name']."作文";
}

/**
 * 根据一级分类type获取二级分类数组
 * @param $id
 * @return string
 */
function getSonCategoryByType($type){
    $list = Config::get("type");
//    print_r($list);exit;
    if(empty($type)){
        return '';
    }
    if(!empty($list)){
        foreach($list as $k=>$v){
            if($v['type'] == $type){
                if(isset($v['son'])){
                    return $v['son'];
                } else {
                    return '';
                }

            }

        }
    }
    return '';
}


function getShijuUrl($id){
    return getDomain()."/shiju/".encodeId($id).".html";
}
function getMShijuUrl($id){
    return getMDomain()."/shiju/".encodeId($id).".html";
}


/**
 * 根据一级分类type获取二级分类数组
 * @param $id
 * @return string
 */
function getSonCategoryById($id,$id2=""){
    $returnType = $returnType2 = [];
    $list = Config::get("type");
    if(empty($id)){
        return '';
    }
    if(!empty($list)){
        $returnType = $list[$id];
        if(!empty($id2) && $id!=$id2){
            $returnType2 = $returnType['son'][$id2];
//            unset($returnType['son']);
        }
    }
    return [$returnType,$returnType2];
}

function getCategoryDataByType($type1,$type2=''){
    $returnType = $returnType2 = [];
    $list = Config::get("type");
//    echo $type1;
//    print_r($list);exit;
    if(empty($type1)){
       return '';
    }
    if(!empty($list)){
        foreach($list as $k=>$v){
            if(!empty($type1)){
                if($v['type'] == $type1){
                    $retuanCategory = $v;
//                    print_r($retuanCategory);exit;
                    unset($retuanCategory['son']);
                    $returnType = $retuanCategory;
//                    print_r($returnType);exit;
                    if(!empty($type2)){
                        if(!empty($v['son'])){
                            foreach($v['son'] as $key=>$val){
                                if($val['type'] == $type2){
                                    $returnType2 = $val;
                                }
                            }
                        }
                    }
                }
            }
        }
    }
//    print_r($returnType);exit;
    return [$returnType,$returnType2];
}

function getCategoryUrl($type,$pid){
    $dir = '';
    if(!empty($pid)){
        $list = Config::get("type");
        $dir = $list[$pid]['type']."/";
    }
    return getDomain()."/".$dir.$type."/";
}
function getMCategoryUrl($type,$pid){
    $dir = '';
    if(!empty($pid)){
        $list = Config::get("type");
        $dir = $list[$pid]['type']."/";
    }
    return getMDomain()."/".$dir.$type."/";
}

function findNum($str=''){
    $str=trim($str);
    if(empty($str)){return '';}
    $temp=array('1','2','3','4','5','6','7','8','9','0');
    $result='';
    for($i=0;$i<strlen($str);$i++){
        if(in_array($str[$i],$temp)){
            $result.=$str[$i];
        }
    }
    return $result;
}


function getContent($content){
    $content = str_replace(['www.baihuawen.cn','白话文'],['',''],$content);
    $isReplace = false;
    $returnData = '';
    $array = explode('</p><p>',$content);
    $end = end($array);
    $end = str_replace(['以上文字','练习机会','需要修改'],['xiaopzireplace','xiaopzireplace','xiaopzireplace'],$end);

    if(strpos($end,'xiaopzireplace')!==false){
        $isReplace = true;
    }
//    print_r($array);
//    var_dump(count($array));exit;
    if($isReplace){
        unset($array[count($array)-1]);
    }
    if(!empty($array)){
        foreach($array as $k=>$v){
            $v = str_replace(['<p>','</p>'],["",""],$v);
            $returnData .="<p>".$v."</p>";

        }
    }
    return $returnData;

}

//汉字字符串转数组
function str_split_unicode($str, $l = 0) {
    if ($l > 0) {
        $ret = array();
        $len = mb_strlen($str, "UTF-8");
        for ($i = 0; $i < $len; $i += $l) {
            $ret[] = mb_substr($str, $i, $l, "UTF-8");
        }
        return $ret;
    }
    return preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY);
}

/**
 * 获取缓存时间
 * @return int
 */
function getCacheRandTime(){
    //2小时  4小时
    return rand(7200,14400);
}

//过滤a标签
function filterA($string){
    if(empty($string)){
        return "";
    }
    $string = htmlspecialchars_decode($string);
    $string = preg_replace("/<a[^>]*>(.*?)<\/a>/is", "$1", $string);
    return $string;
}

//过滤标题特殊字符
function filterTitle($title){
    if(empty($title)){
        return "";
    }
    $searchArr = ['·','，',' (',' )','.','：','/','□','【','】','（','、','）','。','　','〔','《','》','-',':','“','”','—','|'];
    $replaceArr = ["","","","","","","","","","","","","","","","","","","","","","","",""];
    return str_replace($searchArr,$replaceArr,$title);
}

//判断是否是汉字
/**
 * 使用mb_detect_encoding()函数判断字符的字符集是否为UTF-8。
 * 再判断字符的字节数是否大于1，来判断是否为汉字。
 * @param $char
 * @return bool
 */
function isChineseCharacter($char){
    return strlen($char) > 1 && mb_detect_encoding($char,"UTF-8",true);
}


//过滤nbsp
function filterNbsp($string){
    if(empty($string)){
        return "";
    }
    return preg_replace("/(\s|\&nbsp\;|　|\xc2\xa0)/", " ", strip_tags($string));
}

function filterSpecialChars($input) {
    // 使用正则表达式替换非字母、数字、空格的字符
    $return = preg_replace('/[^a-zA-Z0-9 \-]/', '', $input);
    return strtolower(trim($return));
}

function categoryPath(){
    $cacheCategoryAll = "cacheCategoryAll";
    $rs = collection(model('Category')->where(['status'=>'normal'])->order('weigh desc')->cache($cacheCategoryAll)->select())->toArray();
    return $rs;
//    return ['cat-facts'=>'20','cat-breeds'=>'21','cat-guide'=>'22','cat-story'=>'23'];
}

function getAuthor(){
    $arr = ["‌Dr. Claire O'Donnell","‌Dr. Olivia Taylor","‌Dr. Emily Williams","Dr. Sofia González","Dr. Jessica Brown","Dr. Michael Smith","‌Dr. James Thompson","‌Dr. Ryan O'Connor","Dr. Henry Clark","‌Dr. Jonathan Davis"];
    return $arr[mt_rand(0,9)];
}
function filterContent($string){
    if(empty($string)){
        return "";
    }
    return str_replace(['style="text-wrap-mode: nowrap;"'],[""],$string);
}